<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdFormRef">
      <el-form-item
        label="原密码"
        label-width="100px"
        label-position="right"
        prop="old_pwd"
      >
        <el-input v-model="pwdForm.old_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item
        label="新密码"
        label-width="100px"
        label-position="right"
        prop="new_pwd"
      >
        <el-input v-model="pwdForm.new_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item
        label="确认新密码"
        label-width="100px"
        label-position="right"
        prop="re_pwd"
      >
        <el-input v-model="pwdForm.re_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="" label-width="80px">
        <el-button type="primary" @click="doChange">修改密码</el-button>
        <el-button type="info" @click="doReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserPwd',
  data () {
    return {
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 表单校验规则
      pwdFormRules: {
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        re_pwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value !== this.pwdForm.new_pwd) {
                return callback(new Error('两次新密码不一致！'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  // methods:事件处理函数
  methods: {
    doChange () {
      this.$refs.pwdFormRef.validate(async valid => {
        // 通过发送ajax请求
        if (valid) {
          const res = await this.$axios.patch('/my/updatepwd', this.pwdForm)
          console.log(res)
          this.$message.success(res.data.message)
        }
      })
    },
    doReset () {
      // 这个重置是恢复el-form组件的初始状态(文本恢复默认 清除红色提示)
      this.$refs.pwdFormRef.resetFields()
    }
  },
  // 计算属性
  computed: {
    // user() {
    //   return this.$store.state.user
    // }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
